package com.ruoyi.station.controller;

import java.util.*;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.station.domain.*;
import com.ruoyi.station.service.*;
import com.ruoyi.station.util.ParseSql;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 机柜Controller
 *
 * @author ruoyi
 * @date 2021-08-06
 */
@RestController
@RequestMapping("/cabinet")
@Api(value="机柜对象操作资源", tags = "机柜对象操作资源")
public class SMachineCabinetController extends BaseController
{
    @Autowired
    private SMachineCabinetService sMachineCabinetService;
    @Autowired
    private SEquipmentService sEquipmentService;
    @Autowired
    private SDistributionFrameService sDistributionFrameService;
    @Autowired
    private SStationService sStationService;
    @Autowired
    private SMachineRoomService sMachineRoomService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询机柜列表
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:list')")
    @PostMapping("/list")
    @ApiOperation(value="查询机柜列表", notes="查询机柜列表")
    public TableDataInfo query(@ApiParam @RequestBody Map map)
    {

        JSONArray queryData = JSONUtil.parseArray(map.get("queryData"));
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        startPage(pageNum , pageSize);

        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());

        QueryWrapper<SMachineCabinet> wrapper = new QueryWrapper<>();
        Page s = new Page<>(pageNum,pageSize);
        Page<SMachineCabinet> list = sMachineCabinetService.page(s,ParseSql.parse(wrapper, JSONUtil.toList(queryData, QueryData.class),userList));
        for (SMachineCabinet sMachineCabinet : list.getRecords()) {
            //设备
            sMachineCabinet.setSEquipments(sEquipmentService.list(
                    new LambdaQueryWrapper<SEquipment>().eq(SEquipment::getMachineCabinet, sMachineCabinet.getId())));
            //配线架
            sMachineCabinet.setSDistributionFrames(sDistributionFrameService.list(
                    new LambdaQueryWrapper<SDistributionFrame>().eq(SDistributionFrame::getMachineCabinet, sMachineCabinet.getId())));
        }
        return getTableDataInfo(list.getRecords(),list.getTotal());
    }

    /**
     * 查询机柜列表
     */
    @GetMapping("/dictList")
    @ApiOperation(value="查询机柜列表", notes="查询机柜列表")
    public AjaxResult list()
    {
        QueryWrapper<SMachineCabinet> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SMachineCabinet> list = sMachineCabinetService.list(wrapper);
        List<Map> mapList = new ArrayList<>();
        list.stream().forEach(l ->{
            Map<String,Object> map = new HashMap();
            map.put("dictValue",l.getId().toString());
            map.put("dictLabel",l.getMachineCabinetName());
            mapList.add(map);
        });
        return AjaxResult.success(mapList);
    }

    /**
     * 导出机柜列表
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:export')")
    @Log(title = "机柜", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value="导出机柜列表", notes="导出机柜列表")
    public AjaxResult export(@ApiParam SMachineCabinet sMachineCabinet)
    {
        QueryWrapper<SMachineCabinet> wrapper = new QueryWrapper();//通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SMachineCabinet> list = parse(sMachineCabinetService.list(wrapper));
        ExcelUtil<SMachineCabinet> util = new ExcelUtil<SMachineCabinet>(SMachineCabinet.class);
        return util.exportExcel(list, "cabinet");
    }

    /**
     * 导出数据转换
     * @param list
     * @return
     */
    private List<SMachineCabinet> parse(List<SMachineCabinet> list){
        list.stream().forEach(l -> {
            l.setStation(sStationService.getById(l.getStation()).getStationName());
            l.setMachineRoom(sMachineRoomService.getById(l.getMachineRoom()).getMachineRoomName());
            l.setPower(DictUtils.getDictLabel("power_source",l.getPower()));
        });
        return list;
    }
    /**
     * 获取机柜详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取机柜详细信息", notes="获取机柜详细信息")
    public AjaxResult getInfo(@ApiParam @PathVariable("id") String id)
    {
        return AjaxResult.success(sMachineCabinetService.getById(id));
    }

    /**
     * 新增机柜
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:add')")
    @Log(title = "机柜", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value="新增机柜", notes="新增机柜")
    public AjaxResult add(@ApiParam @RequestBody SMachineCabinet sMachineCabinet)
    {
        sMachineCabinet.setCreateBy(SecurityUtils.getUsername());
        int result = sMachineCabinetService.save(sMachineCabinet) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 修改机柜
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:edit')")
    @Log(title = "机柜", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改机柜", notes="修改机柜")
    public AjaxResult edit(@ApiParam @RequestBody SMachineCabinet sMachineCabinet)
    {
        int result = sMachineCabinetService.updateById(sMachineCabinet) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 删除机柜
     */
    @PreAuthorize("@ss.hasPermi('system:cabinet:remove')")
    @Log(title = "机柜", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value="删除机柜", notes="删除机柜")
    public AjaxResult remove(@ApiParam @PathVariable String[] ids)
    {
        List<String> list = Arrays.asList(ids);
        int result = sMachineCabinetService.removeByIds(list) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 导出机柜模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        return AjaxResult.success("DLBDZ_机柜.xls");
    }

    @Log(title = "导入机柜管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:cabinet:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)
    {
        String message = sMachineCabinetService.importsSMachineCabinet(file);
        return AjaxResult.success(message);
    }
}
